package jwt.lab02;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.io.IOException;

public class ReplyLastMessage {

	public static void main(String[] args) throws MessagingException, IOException {
		Properties props = Utils.loadProperties(Utils.PROPERTIES_FILE);

		Message lastMsg = getLastMessage();
		System.out.println("Last message: " + Utils.messageToString(lastMsg));
		if (lastMsg.getAllRecipients() == null || lastMsg.getAllRecipients().length == 0) {
			System.out.println("Last message doesn't have reciepients...");
			return;
		}
		if (lastMsg.getFrom() == null || lastMsg.getFrom().length == 0) {
			System.out.println("Last message doesn't have from adresses");
			return;
		}

		Session session = Session.getDefaultInstance(props, null);

		MimeMessage message = (MimeMessage) lastMsg.reply(true);
		message.setFrom(new InternetAddress(props.getProperty("mail.smtp.from")));
		message.setText("reply to message " + Utils.messageToString(lastMsg));

		System.out.println("Sending message...");

		Transport transport = session.getTransport();
		transport.connect(props.getProperty("mail.smtp.user"), props.getProperty("mail.smtp.password"));
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();

		System.out.println("[ OK ]");
	}

	public static Message getLastMessage() throws MessagingException, IOException {
		Properties props = Utils.loadProperties(Utils.PROPERTIES_FILE);

		Session session = Session.getDefaultInstance(props, null);

		Store store = session.getStore(props.getProperty("mail.store.protocol"));
		store.connect(props.getProperty("mail.pop3.host"), props.getProperty("mail.pop3.user"), props.getProperty("mail.pop3.password"));

		Folder folder = store.getFolder("INBOX");
		folder.open(Folder.READ_ONLY);

		Message message[] = folder.getMessages(), lastMsg = message[message.length - 1];

		lastMsg.getContent();

		folder.close(false);
		store.close();

		return lastMsg;
	}

}
